package com.hjxy.codetools.controller;


import com.github.pagehelper.StringUtil;
import com.hjxy.codetools.dto.PageDto;
import com.hjxy.codetools.interfa.ArtitleServiceInterface;
import com.hjxy.codetools.interfa.TuserServiceInterface;
import com.hjxy.codetools.model.ArtitleModel;
import com.hjxy.codetools.model.SearchForm;
import com.hjxy.codetools.model.TuserModel;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class ArtitleController {

    @Autowired
    ArtitleServiceInterface artitleServiceInterface;
    @Autowired
    TuserServiceInterface tuserServiceInterface;
    /**
     * 前台首页调用
     * 查询最新的前12个文章
     * 不分类别
     * 不分页
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/")
    public String getArtitlesInfo(Model model, HttpServletRequest request) throws Exception {
        Map whMap = new HashMap();
        whMap.put("start",0);
        whMap.put("end", 10);
        List<PageDto> pageDtos=new ArrayList<>();
        List<ArtitleModel> artitleModels = artitleServiceInterface.getArtitlesInfo(whMap);
        if(artitleModels!=null&&artitleModels.size()>0){
            for (ArtitleModel artitleModel:artitleModels) {
                byte[] randcodeByte = Base64.encodeBase64(artitleModel.getRandcode().getBytes());
                artitleModel.setRandcode(new String(randcodeByte));
            }
        }
        int totalNum = artitleServiceInterface.getTotalNum(whMap);
        int totalPage=0;
        if (totalNum>0){
         //存在记录数 计算总共多少页
            if (totalNum<=10) totalPage=1;
            else if (totalNum%10>0)
                totalPage=(totalNum/10)+1;
            else if (totalNum%10==0)
                totalPage=(totalNum/10);
        }
        if (totalPage<=10){
            //前台页数 从 1 到总页数
            for (int i=1;i<=totalPage;i++){
                PageDto pageDto=new PageDto();
                pageDto.setPageIndex(i);
                pageDtos.add(pageDto);
            }
        }
        else if (totalPage>10){
            for (int i=1;i<=10;i++){
                PageDto pageDto=new PageDto();
                pageDto.setPageIndex(i);
                pageDtos.add(pageDto);
            }
        }
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentpage", 1);
        model.addAttribute("pageDtos", pageDtos);
        model.addAttribute("list", artitleModels);
        return "index";
    }

    /**
     * 前台首页调用
     * 不分类别
     * 分页
     * 1-20
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/page/{currentpage}")
    public String getPagePictures(Model model,@PathVariable("currentpage") int currentpage) throws Exception {
        Map whMap = new HashMap();
        whMap.put("start", (currentpage - 1) * 10);
        whMap.put("end", 10);
        List<ArtitleModel> artitleModels = artitleServiceInterface.getArtitlesInfo(whMap);
        if(artitleModels!=null&&artitleModels.size()>0){
            for (ArtitleModel artitleModel:artitleModels) {
                byte[] randcodeByte = Base64.encodeBase64(artitleModel.getRandcode().getBytes());
                artitleModel.setRandcode(new String(randcodeByte));
            }
        }
        List<PageDto> pageDtos=new ArrayList<>();
        int totalNum = artitleServiceInterface.getTotalNum(whMap);
        int totalPage=0;
        if (totalNum>0){
            //存在记录数 计算总共多少页
            if (totalNum<=10) totalPage=1;
            else if (totalNum%10>0)
                totalPage=(totalNum/10)+1;
            else if (totalNum%10==0)
                totalPage=(totalNum/10);
            if (totalPage<=10){
                //前台页数 从 1 到总页数
                for (int i=1;i<=totalPage;i++){
                    PageDto pageDto=new PageDto();
                    pageDto.setPageIndex(i);
                    pageDtos.add(pageDto);
                }
            }
            else if (totalPage>10){
                //前台页数从 当前页往前4页  往后数5页
                if ((currentpage+5)>=totalPage){
                    for (int i=(currentpage-4);i<=totalPage;i++){
                        PageDto pageDto=new PageDto();
                        pageDto.setPageIndex(i);
                        pageDtos.add(pageDto);
                    }
                }
                else{
                    for (int i=(currentpage-4);i<=(currentpage+5);i++){
                        PageDto pageDto=new PageDto();
                        pageDto.setPageIndex(i);
                        pageDtos.add(pageDto);
                    }
                }
            }
        }
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentpage", currentpage);
        model.addAttribute("pageDtos", pageDtos);
        model.addAttribute("list", artitleModels);
        return "page";
    }


    /**
     * 前台首页调用
     * 分类别
     * 分页
     * 1-20
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/page/{typet}/{currentpage}")
    public String getPagePictures(Model model,@PathVariable("typet") String typet,@PathVariable("currentpage") int currentpage) throws Exception {
        Map whMap = new HashMap();
        whMap.put("start", (currentpage - 1) * 10);
        whMap.put("end", 10);
        whMap.put("code",typet);
        List<ArtitleModel> artitleModels = artitleServiceInterface.getArtitlesInfo(whMap);
        if(artitleModels!=null&&artitleModels.size()>0){
            for (ArtitleModel artitleModel:artitleModels) {
                byte[] randcodeByte = Base64.encodeBase64(artitleModel.getRandcode().getBytes());
                artitleModel.setRandcode(new String(randcodeByte));
            }
        }
        List<PageDto> pageDtos=new ArrayList<>();
        int totalNum = artitleServiceInterface.getTotalNum(whMap);
        int totalPage=0;
        if (totalNum>0){
            //存在记录数 计算总共多少页
            if (totalNum<=10) totalPage=1;
            else if (totalNum%10>0)
                totalPage=(totalNum/10)+1;
            else if (totalNum%10==0)
                totalPage=(totalNum/10);
            if (totalPage<=10){
                //前台页数 从 1 到总页数
                for (int i=1;i<=totalPage;i++){
                    PageDto pageDto=new PageDto();
                    pageDto.setPageIndex(i);
                    pageDtos.add(pageDto);
                }
            }
            else if (totalPage>10){
                //前台页数从 当前页往前4页  往后数5页
                if ((currentpage+5)>=totalPage){
                    for (int i=(currentpage-4);i<=totalPage;i++){
                        PageDto pageDto=new PageDto();
                        pageDto.setPageIndex(i);
                        pageDtos.add(pageDto);
                    }
                }
                else{
                    for (int i=(currentpage-4);i<=(currentpage+5);i++){
                        PageDto pageDto=new PageDto();
                        pageDto.setPageIndex(i);
                        pageDtos.add(pageDto);
                    }
                }
            }
        }
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentpage", currentpage);
        model.addAttribute("pageDtos", pageDtos);
        model.addAttribute("list", artitleModels);
        return typet;
    }
    /**
     * 前台调用
     * 根据randcode 获取文章详情
     * 包含前后两条记录
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "/artitle/{randcode}", method = RequestMethod.GET)
    public String artitledetail(Model model, @PathVariable("randcode") String randcode) throws Exception {
        if (!randcode.isEmpty()){
            //base64解密
           String realRandCode=new String(Base64.decodeBase64(randcode));
           if (!StringUtil.isEmpty(realRandCode)){
               if (realRandCode.length()==13){
                   //只有randcode 编码过后
                   ArtitleModel artitleModel = artitleServiceInterface.getArtitleByCode(realRandCode);
                   artitleModel.setRandcode(randcode);
                   model.addAttribute("artitleModel", artitleModel);
                   model.addAttribute("keyTitle",artitleModel.getTitle());
                   if (artitleModel.getNum()!=0){
                       model.addAttribute("needPay",1);
                       artitleModel.setContent(artitleModel.getSummarycontent());
                   }

                   //该行记录 前后两条数据
                   List<ArtitleModel> prenextArtitleModels=artitleServiceInterface.getArtitlePreNext(artitleModel.getId());
                   if (prenextArtitleModels!=null&&prenextArtitleModels.size()>0){
                       if (prenextArtitleModels.size()==1){
                           if(prenextArtitleModels.get(0).getId()>artitleModel.getId())
                           {
                               model.addAttribute("nexttitle",prenextArtitleModels.get(0).getTitle());
                               byte[] randcodeByte = Base64.encodeBase64(prenextArtitleModels.get(0).getRandcode().getBytes());
                               model.addAttribute("nextrandcode",new String(randcodeByte));
                           }
                           else
                           {
                               model.addAttribute("pretitle",prenextArtitleModels.get(0).getTitle());
                               byte[] randcodeByte = Base64.encodeBase64(prenextArtitleModels.get(0).getRandcode().getBytes());
                               model.addAttribute("prerandcode",new String(randcodeByte));
                           }
                       }
                       else if(prenextArtitleModels.size()==2){
                           model.addAttribute("nexttitle",prenextArtitleModels.get(0).getTitle());
                           byte[] randcodeByte = Base64.encodeBase64(prenextArtitleModels.get(0).getRandcode().getBytes());
                           model.addAttribute("nextrandcode",new String(randcodeByte));
                           model.addAttribute("pretitle",prenextArtitleModels.get(1).getTitle());
                           randcodeByte= Base64.encodeBase64(prenextArtitleModels.get(1).getRandcode().getBytes());
                           model.addAttribute("prerandcode",new String(randcodeByte));
                       }
                   }
               }
               else if (realRandCode.length()>13){
                   //前 4位 是 用户名 中间4位是 验证码 最后13位 是文章randcode
                   String yhmCode = new String(realRandCode).substring(0, 4);
                   String verifycode = new String(realRandCode).substring(4, 8);
                   Map whMap=new HashMap();
                   whMap.put("tname",yhmCode);
                   whMap.put("pass",verifycode);
                   List<TuserModel> tuserModels= tuserServiceInterface.getTuserByItem(whMap);
                   if (tuserModels!=null&&tuserModels.size()>0){
                       //用户名 验证码都正确
                       //此时 获取到的 除去用户名 密码以外的字符 仍然是加密后的字符 故而需要再次解密
                       String artitleCode= realRandCode.substring(8, realRandCode.length());
                       //获取时间戳
                       String timeStamp=artitleCode.substring(artitleCode.length()-13,artitleCode.length());
                       long sysTime= System.currentTimeMillis()-Long.valueOf(timeStamp);
                       long ms= TimeUnit.MILLISECONDS.toSeconds(sysTime);
                       //超过10分钟 600s的 忽略
                       if (ms<=600){
                           //此时 前13位是 文章编码 后面字符 是前台js获取的时间戳
                           artitleCode=new String(Base64.decodeBase64(artitleCode.replace(timeStamp,"").getBytes()));

                           ArtitleModel artitleModel = artitleServiceInterface.getArtitleByCode(artitleCode);
                           model.addAttribute("artitleModel", artitleModel);
                           model.addAttribute("keyTitle",artitleModel.getTitle());
                           //无需显示 需要支付获取用户名密码 div
                           model.addAttribute("needPay",0);
                           //该行记录 前后两条数据
                           List<ArtitleModel> prenextArtitleModels=artitleServiceInterface.getArtitlePreNext(artitleModel.getId());
                           if (prenextArtitleModels!=null&&prenextArtitleModels.size()>0){
                               if (prenextArtitleModels.size()==1){
                                   if(prenextArtitleModels.get(0).getId()>artitleModel.getId())
                                   {
                                       model.addAttribute("nexttitle",prenextArtitleModels.get(0).getTitle());
                                       byte[] randcodeByte = Base64.encodeBase64(prenextArtitleModels.get(0).getRandcode().getBytes());
                                       model.addAttribute("nextrandcode",new String(randcodeByte));
                                   }
                                   else
                                   {
                                       model.addAttribute("pretitle",prenextArtitleModels.get(0).getTitle());
                                       byte[] randcodeByte = Base64.encodeBase64(prenextArtitleModels.get(0).getRandcode().getBytes());
                                       model.addAttribute("prerandcode",new String(randcodeByte));
                                   }
                               }
                               else if(prenextArtitleModels.size()==2){
                                   model.addAttribute("nexttitle",prenextArtitleModels.get(0).getTitle());
                                   byte[] randcodeByte = Base64.encodeBase64(prenextArtitleModels.get(0).getRandcode().getBytes());
                                   model.addAttribute("nextrandcode",new String(randcodeByte));
                                   model.addAttribute("pretitle",prenextArtitleModels.get(1).getTitle());
                                   randcodeByte= Base64.encodeBase64(prenextArtitleModels.get(1).getRandcode().getBytes());
                                   model.addAttribute("prerandcode",new String(randcodeByte));
                               }
                           }

                       }


                   }


               }
               else
               {
                   // 错误编码 返回错误页


               }

           }


        }
        return "artitle";
    }




    /**
     * 前台调用
     * 根据分类
     * 进行查询
     * 展示
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/artitles/{typet}/{currentpage}", method = RequestMethod.GET)
    public String TypeArtitles(Model model, @PathVariable("typet") String typet,@PathVariable("currentpage") int currentpage) throws Exception {

        if (!typet.isEmpty()){
            Map whMap = new HashMap();
            whMap.put("start", (currentpage - 1) * 10);
            whMap.put("end", 10);
            whMap.put("code",typet);

            List<ArtitleModel> artitleModels = artitleServiceInterface.TypeArtitles(whMap);
            if(artitleModels!=null&&artitleModels.size()>0){
                for (ArtitleModel artitleModel:artitleModels) {
                    byte[] randcodeByte = Base64.encodeBase64(artitleModel.getRandcode().getBytes());
                    artitleModel.setRandcode(new String(randcodeByte));
                }
            }
            List<PageDto> pageDtos=new ArrayList<>();
            int totalNum = artitleServiceInterface.getTotalNum(whMap);
            int totalPage=0;

            if (totalNum>0){
                //存在记录数 计算总共多少页
                if (totalNum<=10) totalPage=1;
                else if (totalNum%10>0)
                    totalPage=(totalNum/10)+1;
                else if (totalNum%10==0){
                    totalPage=(totalNum/10);
                }


                if (totalPage<=10){
                    //前台页数 从 1 到总页数
                    for (int i=1;i<=totalPage;i++){
                        PageDto pageDto=new PageDto();
//                        pageDto.setNextPage(false);
//                        pageDto.setNextPage(false);
                        pageDto.setPageIndex(i);
                        pageDtos.add(pageDto);
                    }
                }

                else if (totalPage>10){
                    //前台页数从 当前页往前4页  往后数5页
                    if ((currentpage+5)>=totalPage){
                        for (int i=(currentpage-4);i<=totalPage;i++){
                            PageDto pageDto=new PageDto();
//                            pageDto.setNextPage(false);
//                            pageDto.setPrePage(true);
                            pageDto.setPageIndex(i);
                            pageDtos.add(pageDto);
                        }
                    }
                    else{
                        for (int i=(currentpage-4);i<=(currentpage+5);i++){
                            PageDto pageDto=new PageDto();
//                            pageDto.setNextPage(false);
//                            pageDto.setNextPage(false);
                            pageDto.setPageIndex(i);
                            pageDtos.add(pageDto);
                        }
                    }
                }
            }
            model.addAttribute("totalPage", totalPage);
            model.addAttribute("currentpage", currentpage);
            model.addAttribute("pageDtos", pageDtos);
            model.addAttribute("list", artitleModels);

        }
        return typet;
    }

    /**
     * 前台调用
     * 根据用户查询条件查询文章
     * @param searchForm
     * @throws Exception
     */
    @PostMapping("/search")
    public String search(@ModelAttribute("form") SearchForm searchForm,Model model) throws Exception {
            String searchKey=searchForm.getKeytxt();
             List<ArtitleModel> artitleModels = artitleServiceInterface.searchArticles(searchKey);
        if(artitleModels!=null&&artitleModels.size()>0){
            for (ArtitleModel artitleModel:artitleModels) {
                byte[] randcodeByte = Base64.encodeBase64(artitleModel.getRandcode().getBytes());
                artitleModel.setRandcode(new String(randcodeByte));
            }
        }
             model.addAttribute("list", artitleModels);
            return "search";
    }


    /**
     * 前台sitemap调用
     * 获取全部文章
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/sitemap")
    public String sitemap(Model model) throws Exception {
        List<ArtitleModel> artitleModels = artitleServiceInterface.getAllArtitlesInfo();
        if(artitleModels!=null&&artitleModels.size()>0){
            for (ArtitleModel artitleModel:artitleModels) {
                byte[] randcodeByte = Base64.encodeBase64(artitleModel.getRandcode().getBytes());
                artitleModel.setRandcode(new String(randcodeByte));
            }
        }
        model.addAttribute("list", artitleModels);

        return "sitemap";
    }
}
